#!/bin/sh

drive_dir=/tmp/drive

login() 
{
	#create folders to save http responses
	[ ! -d "$dirve_dir" ] && mkdir -p $drive_dir
	
	local usbPath=$(config get usb_path)
	local syncFolder=$(config get sync_local_folder)
	
	if [ -d "$usbPath/$syncFolder" ]; then
		config set drive_folder_invalid=0
	else
		config set drive_folder_invalid=1
	fi

	netdrive --login	

	[ "$(config get amazon_login_status)" != "200" ] && exit 0

	netdrive --endpoint && netdrive --rootid &

	local account=$(config get drive_account)
	local last_account=$(config get last_drive_account)

	if [ -z $last_account ] || [ $account != $last_account ]; then
		config set usb_path=
		config set sync_local_folder=
		config set syncup_folder_id=
		config set amazon_sync=
		config set drive_folder_invalid=0
		config set usb_removed=0
		config set drive_rootID=
		exit 0
	fi

	[ -z $usbPath ] || [ -z $syncFolder ] && exit 0 || cmdsched
}

logout() 
{
	killall netdrive
	rm $drive_dir -rf
	[ $(config set sync_auto) = "1" ] && config set sync_auto=0 && cmdsched && sync_auto=1
	[ $(config set sync_manul) = "1" ] && config set sync_manul=0 && cmdsched && sync_manul=1
	cmdsched
	config set last_drive_account=$(config get drive_account)
	config set drive_usb_removed=0
}

saveDir() #1: 0:initial save 1:save and delete 2:save but not delete
{
	local bk_pid=$(ps |grep "netdrive --backup" |grep -v "grep" |awk -F " " '{print $1}')
	if [ ! -z $bk_pid ]; then
		kill $bk_pid	
	fi

	local usbPath=$(config get usb_path)

	if [ -z $(echo $usbPath |grep tmp) ]; then
		usbPath="/tmp$usbPath"
		config set usb_path=$usbPath	
	fi
	
	#get usb serial number
	local sd=`echo $usbPath |awk -F "/" '{print $NF}' |awk -F "" '{print $1$2$3}'`	
	local num=`ls /sys/block/$sd/device/scsi_device |awk -F ":" '{print $1}'`
	local serial=`cat /proc/scsi/usb-storage/$num |grep "Serial" |awk '{print $NF}'`
	config set usb_serial=$serial

	[ -s $usbPath/.cloudBackup ] && rm $usbPath/.cloudBackup && rm $usbPath/.amazon_Sync_errorMsg

	config set amazon_sync=
	local sync_id=$(config get syncup_folder_id)
	[ ! -z $sync_id ] && config set last_sync_folder_id=$sync_id && config set syncup_folder_id=

	cmdsched
}

checkname()
{
	killall netdrive
	config set amazon_sync=
	echo "BEGIN" > /tmp/drive/backupSize

	echo "[Cloud Backup]Check folder name. Please wait..."
	local folder_name=$(config get sync_local_folder)
	netdrive --checkname --name "$folder_name"
}

checkcfl() #1: option
{
	local cfl_id=$(config get amazon_cfl_id)
	if [ $1 = "1" ]; then
		config set backup_cfl=1	
		#local folder_name=$(config get sync_local_folder)
		#local new_name="$folder_name-CloudBackup"
		#netdrive --rename --name $new_name --id $cfl_id
	else
		config set backup_cfl=2	
		#netdrive --delete --id $cfl_id
	fi
}

detCloud()
{
	[ "x$(ps |grep "netdrive --backup" |grep -v grep |grep -v netdrive.sh)" != "x" ] && echo "[Cloud Backup]Last Backup has not Finished!" && exit 0	
	
	[ $(config get usb_removed) = "1" ] || [ $(config get drive_folder_invalid) = "1" ] && echo "[Cloud Backup]No USB or Folder invalid" && exit 0
	
	local usbPath=$(config get usb_path)
	local folderName=$(config get sync_local_folder)
	local id=$(config get syncup_folder_id)
	[ -z $usbPath ] || [ -z $folderName ] || [ -z $id ] && exit 0

	local pathname="$usbPath/$folderName"
	[ ! -d $pathname ] && echo "[Cloud Backup]Backup folder invalid" && exit 0
	echo "Detect $pathname"
	netdrive --detCloud --id $id --pathname "$pathname"
	netdrive --backup &	
	config set amazon_sync=
}

check()
{
	local usbPath=$(config get usb_path)
	local syncFolder=$(config get sync_local_folder)
	
	#[ "$(config get drive_folder_invalid)" = 1 ] && exit 0 
	
	[ -z $usbPath ] || [ -z $syncFolder ] && exit 0

	if [ -d "$usbPath/$syncFolder" ]; then
		config set drive_folder_invalid=0
		#config set amazon_sync=
	else
		config set drive_folder_invalid=1
		echo "[Cloud Backup]Your selected folder is invalid now"
		config set backup_error_other="[Cloud Backup]Your selected folder is invalid now"
		config set amazon_sync=-2
		/etc/email/send_email_alert amazon_cloud_backup drive_folder_invalid
        logger -- "[Cloud Backup]Your selected folder is invalid now,"
	fi
}

opt() #$1: 1,2,3
{
	local usbPath=$(config get usb_path)
	config set usb_removed=0	
	config set drive_folder_invalid=0
	
	if [ $1 -eq 2 ]; then #recover
		echo "$[Cloud Backup]recover"
		local id=$(config get last_sync_folder_id)
		local name=$(config get last_sync_folder)
		local pathname="$usbPath/$name"
		while [ -d "$usbPath/$name" ]
		do
			name="$name-CloudBackupRecover"
			pathname="$usbPath/$name"
		done
		netdrive --recover --name "$name" --pathname "$pathname" --id $id & 
	elif [ $1 -eq 3 ]; then #delete 
		echo "[Cloud Backup]Delete"
		local id=$(config get last_sync_folder_id)
		netdrive --id $id --delete &
	fi
}

mount() #1:sd**
{
	local usb_serial=$(config get usb_serial)
	[ -z $usb_serial ] && config set usb_removed=0 && exit 0

	local usbPath=$(config get usb_path)
	
	local sd_num=`echo $1 |cut -b 13`
	local sd=`echo $1 |cut -b '1-3'`
	local num=`ls /sys/block/$sd/device/scsi_device |awk -F ":" '{print $1}'`
	local serial=`cat /proc/scsi/usb-storage/$num |grep "Serial" |awk '{print $NF}'`
	if [ $serial = $usb_serial ] && [ "$sd_num" = "`echo $usbPath |cut -b 13`" ]; then
		config set usb_removed=0
		
		config set usb_path="/tmp/mnt/$1"
		if [ "$(config get amazon_sync)" = "-2" ] && [ "$(config get drive_usb_removed)" = "1" ]; then
			config set drive_usb_removed=0
			config set drive_folder_invalid=0
			echo "[Cloud Backup]Continue last Backup"
			netdrive --backup > /dev/console &	
		fi
		cmdsched
		exit 0
	fi

	#get usb serial number
	local sd_org=`echo $usbPath |awk -F "/" '{print $NF}' |cut -b '1-3'`	
	local num_org=`ls /sys/block/$sd_org/device/scsi_device |awk -F ":" '{print $1}'`
	local serial_org=`cat /proc/scsi/usb-storage/$num_org |grep "Serial" |awk '{print $NF}'`
	[ $serial_org = $usb_serial ] && config set usb_removed=0 && exit 0 
	#[ "$(config get drive_usb_removed)" != "1" ] && cmdsched && exit 0 
	
	config set usb_removed=1
}

umount() #1:sd**
{
   notify_stop()
	local sd=`echo $1 |cut -b '1-3'`
	local num=`ls /sys/block/$sd/device/scsi_device |awk -F ":" '{print $1}'`
	local serial=`cat /proc/scsi/usb-storage/$num |grep "Serial" |awk '{print $NF}'`
	[ $serial != $(config get usb_serial) ] && exit 0
	
	config set usb_removed=1
	if [ "$(config get amazon_sync)" = "1" ]; then
		config set amazon_sync=-2
		echo "BEGIN" > /tmp/drive/backupSize
		config set drive_usb_removed=1
		echo "[Cloud Backup]Your hard disk has removed"
		echo "[Cloud Backup]Your selected folder is invalid now"
		config set backup_error_other="[Cloud Backup]Your hard disk has removed, your selected folder is invalid now"
		config set drive_folder_invalid=1
		/etc/email/send_email_alert amazon_cloud_backup drive_usb_removed
        logger -- "[Cloud Backup]Your hard disk has removed,"
		/etc/email/send_email_alert amazon_cloud_backup drive_folder_invalid
        logger -- "[Cloud Backup]Your selected folder is invalid now,"
	fi
	
	[ "$(config get sync_auto)" = "1" ] && config set sync_auto=0 && cmdsched && config set sync_auto=1
	[ "$(config get sync_manul)" = "1" ] && config set sync_manul=0 && cmdsched && config set sync_manul=1
}

notify_bk()
{
    auto_enable=`config get sync_auto`
    nusb_path=`config get usb_path`
    nfolder=`config get sync_local_folder`
    if [ "$auto_enable" = "1" -a "x$nusb_path" != "x" -a "x$nfolder" != "x" ]; then
        ndir="$nusb_path/$nfolder"
        echo "notify listen  $ndir ........."
        killall inotifywait
        rm /tmp/even_w
        /usr/sbin/inotifywait -rqm --format '%w|%e|%f' -e modify -e moved_from -e moved_to -e create -e delete $ndir -o /tmp/even_w &
        killall netdrive
        echo 0 > /tmp/bk_status
        /usr/sbin/netdrive --backup > /dev/console &
        while [ 1 ]; do
            [ -f /tmp/bk_status ] && bk_done=`cat /tmp/bk_status`
            if [ "$bk_done" = "1" ]; then #finish backup
                while [ 1 ]; do
                    echo 0 > /tmp/notify_status
                    if [ -s /tmp/even_w ]; then
                        /usr/sbin/netdrive --notify > /dev/console &
                        while [ 1 ]; do
                            [ -f /tmp/notify_status ] && notify_done=`cat /tmp/notify_status`
                            if [ "$notify_done" = "1" ]; then #finish backup
                                echo "notify this file/folder is done" > /dev/console
                                break
                            else
                                sleep 10
                            fi
                        done
                    else
                        config set notify_name=
                        config set notify_kind=
                        config set notify_path=
                        config set notify_action=
                    fi
                        sleep 10
                done
            else
                sleep 20
            fi
        done
    fi
}

auto()
{
	local det_pid=$(ps |grep "netdrive --detCloud" |grep -v "grep" |awk -F " " '{print $1}')
	while [ ! -z $det_pid ]
	do
		echo "wait"
		sleep 2
		det_pid=$(ps |grep "netdrive --detCloud" |grep -v "grep" |awk -F " " '{print $1}')
	done
	
	[ "x$(ps |grep "netdrive --backup" |grep -v grep |grep -v netdrive.sh)" != "x" ] && echo "[Cloud Backup]Last Backup has not Finished!" && exit 0	
	[ "x$(config get drive_contentUrl)" = "x" ] || [ "x$(config get drive_metadataUrl)" = "x" ] && netdrive --endpoint
	if [ "x$(config get drive_contentUrl)" = "x" ] || [ "x$(config get drive_metadataUrl)" = "x" ]; then
		config set amazon_sync=-2
		config set backup_error_other="[Cloud Backup]Backup failed due to unknown error"
		/etc/email/send_email_alert amazon_cloud_backup unknown_error 
        logger -- "[Cloud Backup]Backup failed due to unknown error,"
		echo "[Cloud Backup Error]Fail to get endpoint" && exit 0
	fi

	[ ! -d "/tmp/drive" ] && mkdir -p "/tmp/drive"
	config set amazon_sync=1
	config set usb_removed=0
	config set drive_usb_removed=0
	config set drive_folder_invalid=0
	echo "BEGIN" > /tmp/drive/backupSize
	netdrive --backup > /dev/console & 
}

manul()
{
	local det_pid=$(ps |grep "netdrive --detCloud" |grep -v "grep" |awk -F " " '{print $1}')
	while [ ! -z $det_pid ]
	do
		echo "wait"
		sleep 2	
		det_pid=$(ps |grep "netdrive --detCloud" |grep -v "grep" |awk -F " " '{print $1}')
	done
	
	[ "x$(ps |grep "netdrive --backup" |grep -v grep |grep -v netdrive.sh)" != "x" ] && echo "[Cloud Backup]Last Backup has not Finished!" && exit 0	
	[ "x$(config get drive_contentUrl)" = "x" ] || [ "x$(config get drive_metadataUrl)" = "x" ] && netdrive --endpoint
	if [ "x$(config get drive_contentUrl)" = "x" ] || [ "x$(config get drive_metadataUrl)" = "x" ]; then
		config set amazon_sync=-2
		config set backup_error_other="[Cloud Backup]Backup failure due to unknown error"
		/etc/email/send_email_alert amazon_cloud_backup unknown_error 
        logger -- "[Cloud Backup]Backup failure due to unknown error,"
		echo "[Cloud Backup Error]Fail to get endpoint" && exit 0
	fi

	[ ! -d "/tmp/drive" ] && mkdir -p "/tmp/drive"
	config set amazon_sync=1
	config set usb_removed=0
	config set drive_usb_removed=0
	config set drive_folder_invalid=0
	echo "BEGIN" > /tmp/drive/backupSize
	netdrive --backup > /dev/console &
}

notify_stop()
{
    local nt_p=`ps -w |grep notify_bk |grep -v "grep" | awk '{print $1}'`
    if [ "x$nt_p" != "x" ]; then
        /bin/kill $nt_p
    fi
    local nt_w=`ps -w |grep inotifywait |grep -v "grep" | awk '{print $1}'`
    if [ "x$nt_w" != "x" ]; then
        /bin/kill $nt_w
    fi
}

case "$1" in
	login)
	login
	;;
	logout)
	logout
	;;
	auto)
	auto
	;;
	notify_bk)
	notify_bk 
	;;
	manul)
	manul
	;;
	save)
	saveDir $2
	;;
	check)
	check
	;;
	opt)
	opt $2
	;;
	mount)
	mount $2
	;;
	umount)
	umount $2
	;;
	checkname)
	checkname
	;;
	cfl)
	checkcfl $2
	;;
	detCloud)
	detCloud
	;;
	notify_stop)
	notify_stop
	;;
	*)
	echo "Usage: $0 {login|logout|auto|notify_bk|manul|save|check|opt|notify_stop}"
	exit 1
esac

exit 0
